package com.techsoul.module.accounting.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.techsoul.common.core.exception.ParamException;
import com.techsoul.common.core.pojo.vo.UserVo;
import com.techsoul.common.core.util.ServletUtils;
import com.techsoul.common.core.util.bean.BeanUtils;
import com.techsoul.common.core.util.collection.ListUtils;
import com.techsoul.common.core.util.id.IdWorker;
import com.techsoul.common.core.util.lang.DateUtils;
import com.techsoul.common.core.util.lang.NumberUtils;
import com.techsoul.common.core.util.lang.StringUtils;
import com.techsoul.common.security.service.TokenService;
import com.techsoul.module.accounting.enmus.AccountingStatusEnum;
import com.techsoul.module.accounting.mapper.AccAccountingApHisMapper;
import com.techsoul.module.accounting.pojo.entity.AccAccountingApHis;
import com.techsoul.module.accounting.pojo.entity.AccountingAp;
import com.techsoul.module.accounting.pojo.param.AccAccountingApHisSaveParam;
import com.techsoul.module.accounting.pojo.param.AccAccountingApHisSearchParam;
import com.techsoul.module.accounting.pojo.param.AccountingApSearchParam;
import com.techsoul.module.accounting.pojo.param.MaterialBuyPriceSearchParam;
import com.techsoul.module.accounting.pojo.vo.AccAccountingApHisVo;
import com.techsoul.module.accounting.pojo.vo.AccountingApVo;
import com.techsoul.module.accounting.pojo.vo.MaterialBuyPriceVo;
import com.techsoul.module.accounting.service.IAccAccountingApHisService;
import com.techsoul.module.accounting.service.IMaterialBuyPriceService;
import com.techsoul.module.basic.mapper.StoreMapper;
import com.techsoul.module.basic.pojo.entity.Store;
import com.techsoul.module.goods.mapper.SpuMapper;
import com.techsoul.module.goods.pojo.vo.SpuVo;
import com.techsoul.module.order.enmus.ReturnOrderStatusEnum;
import com.techsoul.module.order.enmus.SalesOrderStatusEnum;
import com.techsoul.module.order.pojo.entity.ReturnOrderItem;
import com.techsoul.module.order.pojo.entity.SalesOrderItem;
import com.techsoul.module.order.pojo.param.*;
import com.techsoul.module.order.pojo.vo.SalesOrderItemHisVo;
import com.techsoul.module.order.pojo.vo.SalesOrderItemVo;
import com.techsoul.module.order.service.ISalesOrderItemHisService;
import com.techsoul.module.system.enmus.ErrorType;
import com.techsoul.module.system.mapper.OperationLogMapper;
import com.techsoul.module.system.pojo.entity.OperationLog;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * 财务应付 Service实现
 * 
 * @author liuen
 * @date 2021-07-31
 */
@Service
@Transactional(readOnly = true)
public class AccAccountingApHisServiceImpl implements IAccAccountingApHisService {

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private AccAccountingApHisMapper mapper;

    @Autowired
    private TokenService tokenService;
    @Autowired
    private ISalesOrderItemHisService salesOrderItemHisService;
    @Autowired
    private OperationLogMapper operationLogMapper;

    @Autowired
    private StoreMapper storeMapper;

    @Autowired
    private SpuMapper spuMapper;
    @Autowired
    private IMaterialBuyPriceService materialBuyPriceService;


    /**
     * 新增
     * @param params
     * @return
     */
    @Transactional(readOnly = false)
    @Override
    public String insert(AccAccountingApHisSaveParam params) {
        UserVo user = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();
        AccAccountingApHis entity = new AccAccountingApHis();
        BeanUtils.copyProperties(params, entity);
        entity.setId(idWorker.nextId() + "").preInsert(user.getId());
        this.mapper.insert(entity);
        return entity.getId();
    }

    /**
     * 删除
     * @param id
     * @return
     */
    @Transactional(readOnly = false)
    @Override
    public Integer delete(String id) {
        return this.mapper.deleteById(id);
    }

    /**
     * 批量删除
     * @param idList
     */
    @Transactional(readOnly = false)
    @Override
    public Integer batchDelete(List<String> idList) {
        if (ListUtils.isNotEmpty(idList)) {
            return this.mapper.deleteBatchIds(idList);
        } else {
            return 0;
        }
    }

    /**
     * 修改
     * @param params
     * @return
     */
    @Transactional(readOnly = false)
    @Override
    public Integer update(AccAccountingApHisSaveParam params) {
        AccAccountingApHis entityFromDb = this.mapper.selectById(params.getId());
        if (entityFromDb == null) {
            throw new ParamException("id=" + params.getId());
        }
        UserVo user = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();
        BeanUtils.copyProperties(params, entityFromDb);
        entityFromDb.preUpdate(user.getId());
        return this.mapper.updateById(entityFromDb);
    }

    /**
     * 详情
     * @param id
     * @return
     */
    @Override
    public AccAccountingApHisVo findById(String id) {
        return this.mapper.findById(id);
    }

    /**
     * 列表
     * @param params
     * @return
     */
    @Override
    public List<AccAccountingApHisVo> findAll(AccAccountingApHisSearchParam params) {
        return this.mapper.findAll(params);
    }

    /**
     * 列表-分页
     * @param params
     * @param current
     * @param pageSize
     * @return
     */
    @Override
    public IPage<AccAccountingApHisVo> findAll(AccAccountingApHisSearchParam params, Integer current, Integer pageSize) {
        return this.mapper.findAll(new Page<>(current, pageSize), params);
    }
    @Transactional(readOnly = false)
    @Override
    public String generateMigrationArAp(UserVo userVo){
        SalesOrderItemHisSearchParam salesOrderItemSearchParam = new SalesOrderItemHisSearchParam();
        salesOrderItemSearchParam.setStatus(SalesOrderStatusEnum.NEWREC.getValue());
        salesOrderItemSearchParam.setErrorFlag("N");
        String rt = "success";
        List<SalesOrderItemHisVo> notSettlements = this.salesOrderItemHisService.findAll(salesOrderItemSearchParam);
        for(int i = 0; i < notSettlements.size(); i++){
            SalesOrderItemHisVo salesOrderItemVo =(SalesOrderItemHisVo)notSettlements.get(i);
            if(StringUtils.isNull(salesOrderItemVo.getCustRelSalesPrice())){
                salesOrderItemVo.setGenAccFailedReason("和营销委结算价为空");
                this.genOperationLog(salesOrderItemVo,userVo);
                SalesOrderItemHisSaveParam salesOrderItemSaveParam = new SalesOrderItemHisSaveParam();
                salesOrderItemVo.setStatus(SalesOrderStatusEnum.ACC_FAILED.getValue());
                BeanUtils.copyProperties(salesOrderItemVo, salesOrderItemSaveParam);
                this.salesOrderItemHisService.update(salesOrderItemVo.getId(), salesOrderItemSaveParam);
                continue;
            }
            rt = this.getCustomerArAmount(salesOrderItemVo,userVo);
        }
        return rt;
    }

    @Transactional(readOnly = false)
    @Override
    public String fixData(UserVo userVo) {
        AccAccountingApHisSearchParam searchParam = new AccAccountingApHisSearchParam();
        searchParam.setStatus(AccountingStatusEnum.needFix.getStatus());
        List<AccAccountingApHisVo> needFix = this.mapper.findAll(searchParam);
        for (int i = 0; i < needFix.size(); i++) {
            AccAccountingApHisVo accountingAp = (AccAccountingApHisVo)needFix.get(i);
            if(StringUtils.isNull(accountingAp.getPayCust())){
                Store store = this.storeMapper.findStoreByCode(accountingAp.getStoreId());
                if(store!=null){
                    accountingAp.setPayCust(store.getSupplierId()); // 付出去的 收款人
                    accountingAp.setShipperName(store.getSupplierName());
                    accountingAp.setOriginalCustName(store.getSupplierName());
                    accountingAp.setStatus(AccountingStatusEnum.needFix.getEventCode());
                    AccAccountingApHis entityFromDb = new AccAccountingApHis();

                    BeanUtils.copyProperties(accountingAp, entityFromDb);
                    entityFromDb.preUpdate(userVo.getId());
                    this.mapper.updateById(entityFromDb);
                }
            }
        }
        return "success";
    }

    @Transactional(readOnly = false)
    @Override
    public void genOperationLog(SalesOrderItemHisVo data,UserVo user ) {
        OperationLog operationLog = new OperationLog();
        operationLog.setOperationType(ErrorType.ORDERIMPORT.getStatusName());
        operationLog.setErrorMsg(data.getImportErrorMesg());
        operationLog.setMethod(data.getErrorCode());
        operationLog.setLocation(data.getCustSalesOrderNo());
        operationLog.setId(idWorker.nextId() + "").preInsert(user.getId());
        if (user != null) {
            operationLog.setOperatorName(user.getUserName() + "(" + user.getNickName() + ")");
        }
        operationLogMapper.insert(operationLog);

    }
    @Transactional(readOnly = false)
    @Override
    public void genOperationLog(ReturnOrderItem data, UserVo user ) {
        OperationLog operationLog = new OperationLog();
        operationLog.setOperationType(ErrorType.RTORDERIMPORT.getStatusName());
        operationLog.setErrorMsg(data.getImportErrorMesg());
        operationLog.setMethod(data.getErrorCode());
        operationLog.setLocation(data.getCustSalesOrderNo());
        operationLog.setId(idWorker.nextId() + "").preInsert(user.getId());
        if (user != null) {
            operationLog.setOperatorName(user.getUserName() + "(" + user.getNickName() + ")");
        }
        operationLogMapper.insert(operationLog);

    }
    /**
     * 生成财务应付数据
     * @param apamt
     * @param salesOrderItem
     * @return
     */
    @Transactional(readOnly = false)
    @Override
    public String generateApList(Double apamt, SalesOrderItemHisVo salesOrderItem, UserVo userVo){
        AccAccountingApHis accountingAp = new AccAccountingApHis();
        Double rate = NumberUtils.div(apamt.doubleValue(),salesOrderItem.getQty());
        accountingAp.setAmount(new BigDecimal(apamt));
        if(salesOrderItem.getQty()!=null){
            accountingAp.setOriginalSellQty(Long.valueOf(salesOrderItem.getQty().intValue()));
        }
        if(!StringUtils.isNull(salesOrderItem.getCustRelSalesPrice())){
            accountingAp.setContractAmount(new BigDecimal(Double.valueOf(salesOrderItem.getCustRelSalesPrice()))); //营销委结算价
        }
        if(salesOrderItem.getPayMoney()!=null) {
            accountingAp.setAmtAr(salesOrderItem.getPayMoney());
        }else{
            if(!StringUtils.isNull(salesOrderItem.getCustRelSalesPrice())){
                accountingAp.setAmtAr(new BigDecimal(salesOrderItem.getCustRelSalesPrice()));
            }

        }
        if(salesOrderItem.getReturnAmt()!=null&&accountingAp.getAmtAr()!=null){

            BigDecimal amt =accountingAp.getAmtAr().add(salesOrderItem.getReturnAmt());

            accountingAp.setSalesOriginAmount(amt);
        }else{
            accountingAp.setSalesOriginAmount(accountingAp.getAmtAr());
        }
        if(salesOrderItem.getAmtGenAr()!=null){
            accountingAp.setAmtGenAr(String.valueOf(salesOrderItem.getAmtGenAr()));
            Double sellPriceTot = NumberUtils.mul(salesOrderItem.getAmtGenAr(),salesOrderItem.getQty());
            accountingAp.setAmtCur(new BigDecimal(sellPriceTot));
        }
        accountingAp.setCustRelSalesUnitPrice(salesOrderItem.getCustRelSalesUnitPrice());
        accountingAp.setBasicNo(salesOrderItem.getSalesOrderNo());
        // 对方子订单号
        accountingAp.setSourceItemId(salesOrderItem.getCustSalesOrderItemNo());
        accountingAp.setCustSkuId(salesOrderItem.getCustSkuId());
        accountingAp.setCustSpuId(salesOrderItem.getCustSpuId());
        accountingAp.setOrderItemNo(salesOrderItem.getId());

        if(!StringUtils.isNull(salesOrderItem.getCustSkuId())){
            accountingAp.setCargoObjectNo(salesOrderItem.getCustSkuId());
        }else{
            accountingAp.setCargoObjectNo(salesOrderItem.getCustSpuId());
        }
        accountingAp.setCargoObjectName(salesOrderItem.getSkuName());

        accountingAp.setCustSaleUnitPrice(salesOrderItem.getCustSaleUnitPrice());
        accountingAp.setCustSaleUnitMile(salesOrderItem.getCustSaleUnitMile());
        if(!StringUtils.isNull(salesOrderItem.getCustCashPaymentAmt())){
            if(StringUtils.isDouble(salesOrderItem.getCustCashPaymentAmt())){
                accountingAp.setCustCashPaymentAmt(new BigDecimal(Double.valueOf(salesOrderItem.getCustCashPaymentAmt())));
            }else{
                String amt = salesOrderItem.getCustCashPaymentAmt().substring(1);
                accountingAp.setCustCashPaymentAmt(new BigDecimal(Double.valueOf(amt)));

            }
        }
        if(!StringUtils.isNull(salesOrderItem.getCustMilePaymentAmt())){
            if(StringUtils.isDouble(salesOrderItem.getCustMilePaymentAmt())){
                accountingAp.setCustMilePaymentAmt(new BigDecimal(Double.valueOf(salesOrderItem.getCustMilePaymentAmt())));
            }else{
                String amt = salesOrderItem.getCustMilePaymentAmt().substring(1);
                accountingAp.setCustMilePaymentAmt(new BigDecimal(Double.valueOf(amt)));

            }
        }

        accountingAp.setDiscountActivityCode(salesOrderItem.getDiscountActivityCode());
        accountingAp.setStoreDiscountActId(salesOrderItem.getStoreDiscountActId());
        accountingAp.setStoreDiscountCode(salesOrderItem.getStoreDiscountCode());
        accountingAp.setStoreDiscountAmt(salesOrderItem.getStoreDiscountAmt());
        accountingAp.setStoreDiscountAmtPoint(salesOrderItem.getStoreDiscountAmtPoint());
        accountingAp.setMallName(salesOrderItem.getCustomerName());
        accountingAp.setStoreName(salesOrderItem.getStoreName());
        accountingAp.setShipperName(salesOrderItem.getSupplierName());
        accountingAp.setOriginalCustName(salesOrderItem.getSupplierName());

        if(!StringUtils.isNull(salesOrderItem.getSupplierNo())){
            accountingAp.setPayCust(salesOrderItem.getSupplierNo()); // 付出去的 收款人
            accountingAp.setShipperName(salesOrderItem.getSupplierName());
            accountingAp.setOriginalCustName(salesOrderItem.getSupplierName());
        }else{
            Store store = this.storeMapper.findStoreByCode(salesOrderItem.getStoreId());
            if(store!=null){
                accountingAp.setPayCust(store.getSupplierId()); // 付出去的 收款人
                accountingAp.setShipperName(store.getSupplierName());
                accountingAp.setOriginalCustName(store.getSupplierName());
            }

        }


        accountingAp.setBillToCust(salesOrderItem.getMallBuyerNo()); // 付款人
        accountingAp.setPaiedFee(new BigDecimal(0.0));
        accountingAp.setConsigneeName(salesOrderItem.getConsigneeName());

        accountingAp.setContractRate(new BigDecimal(apamt));
        accountingAp.setFrtCd("10001");
        accountingAp.setFrtNm("purchase");
        accountingAp.setInputType("A");
        accountingAp.setMallId(salesOrderItem.getCustomerNo());
        accountingAp.setStoreId(salesOrderItem.getStoreId());

        accountingAp.setStatus(AccountingStatusEnum.CREATED.getStatus());
        accountingAp.setJobDate(DateUtils.formatDate(salesOrderItem.getCreateTime()));
        accountingAp.setOrderSeqNo(salesOrderItem.getSalesOrderId());
        accountingAp.setOriginalCustName(salesOrderItem.getMallBuyerNo());
        accountingAp.setRate(new BigDecimal(rate));
        accountingAp.setRemainedAmount(new BigDecimal(apamt));
        accountingAp.setSite(userVo.getOrgId());
        accountingAp.setReturnAmt(salesOrderItem.getReturnAmt());
        accountingAp.setReturnQty(salesOrderItem.getReturnQty());
        accountingAp.setReturnOrderItemNo(salesOrderItem.getReturnOrderItemNo());

        SpuVo spu =spuMapper.findById(salesOrderItem.getSpuId());
        if(spu!=null){
            accountingAp.setBrandName(spu.getBrandName());
        }
        accountingAp.setWtCnt(new BigDecimal(salesOrderItem.getQty()));
        String[] jobdt = accountingAp.getJobDate().split("-");
        accountingAp.setMonthYear(jobdt[0].concat("-").concat(jobdt[1]));

        accountingAp.setId(idWorker.nextId() + "").preInsert(userVo.getId());
        this.mapper.insert(accountingAp);

        return "success";
    }

    /**
     * 获得供应商付款金额
     * @param salesOrderItem
     *
     * @return
     */
    @Transactional(readOnly = false)
    @Override
    public String getCustomerArAmount(SalesOrderItemHisVo  salesOrderItem,UserVo userVo){
        Double apamt = 0.0;
        String rt = "success";
        String itemErrorMsg = "结算生成：";
        String disctFlag = "N";


        Date today = new Date();


        MaterialBuyPriceSearchParam materialBuyPriceSearchParam = new MaterialBuyPriceSearchParam();




        if(apamt==0.0) {
            // 查正常活动
            SalesOrderItemSaveParam salesOrderItemSaveParam = new SalesOrderItemSaveParam();

            materialBuyPriceSearchParam.setMallCustNo(salesOrderItem.getCustomerNo());
            materialBuyPriceSearchParam.setApplyDate(DateUtils.formatDateTime(salesOrderItem.getCreateTime()));


            materialBuyPriceSearchParam.setSupplierNo(salesOrderItem.getSupplierNo());
            if(!StringUtils.isNull(salesOrderItem.getMaterialMapId())){
                materialBuyPriceSearchParam.setMaterialMapId(salesOrderItem.getMaterialMapId());
                apamt= this.getBuyTotalAmount(salesOrderItem, materialBuyPriceSearchParam);
                if(apamt==0.0) {
                    materialBuyPriceSearchParam.setMaterialMapId(null);
                    materialBuyPriceSearchParam.setMaterialMapId(null);
                    materialBuyPriceSearchParam.setCsaSkuCode("通用");
                    materialBuyPriceSearchParam.setCsaSpuCode(salesOrderItem.getCustSpuId());
                    apamt= this.getBuyTotalAmount(salesOrderItem, materialBuyPriceSearchParam);
                }

            }else  if(!StringUtils.isNull(salesOrderItem.getGoodGroupId())){
                materialBuyPriceSearchParam.setGoodGroupId(salesOrderItem.getGoodGroupId());
                apamt= this.getBuyTotalAmount(salesOrderItem, materialBuyPriceSearchParam);
            }

        }else{
            disctFlag = "Y";
        }


        if (!StringUtils.isNull(salesOrderItem.getStoreDiscountCode())
                &&salesOrderItem.getStoreDiscountCode()!="") {//搞活动
            Double storeDiscount = 0.0;
            String storedisctflag = "N";
            double storeCuponDisct = 0.0;
            if(salesOrderItem.getStoreDiscountAmt()!=null){
                if(salesOrderItem.getStoreDiscountAmt()!=null){
                    storeDiscount = salesOrderItem.getStoreDiscountAmt().doubleValue();
                    storeCuponDisct = NumberUtils.add(storeCuponDisct,storeDiscount);
                }

                if(!StringUtils.isNull(salesOrderItem.getActivityName())){
                    if(salesOrderItem.getActivityName().contains("直播")||salesOrderItem.getActivityName().contains("秒杀"))
                        apamt = NumberUtils.sub(apamt,storeCuponDisct);
                }

                if(!StringUtils.isNull(salesOrderItem.getCustRelSalesPrice())){
                    Double ar = NumberUtils.sub(Double.valueOf(salesOrderItem.getCustRelSalesPrice()),storeCuponDisct);
                    salesOrderItem.setPayMoney(BigDecimal.valueOf(ar));
                }
                storedisctflag = "Y";
            }
            if(salesOrderItem.getStoreDiscountAmtPoint()!=null){
                storeDiscount = NumberUtils.mul(salesOrderItem.getStoreDiscountAmtPoint().doubleValue(),0.05);
                storeCuponDisct = NumberUtils.add(storeCuponDisct,storeDiscount);
                if(!StringUtils.isNull(salesOrderItem.getActivityName())){
                    if(salesOrderItem.getActivityName().contains("直播")||salesOrderItem.getActivityName().contains("秒杀"))
                        apamt = NumberUtils.sub(apamt,storeCuponDisct);
                }

                if(!StringUtils.isNull(salesOrderItem.getCustRelSalesPrice())){
                    Double ar = NumberUtils.sub(Double.valueOf(salesOrderItem.getCustRelSalesPrice()),storeCuponDisct);
                    salesOrderItem.setPayMoney(BigDecimal.valueOf(ar));
                }

                storedisctflag = "Y";
            }
        }


        SalesOrderItemHisSaveParam salesOrderItemSaveParam = new SalesOrderItemHisSaveParam();
        salesOrderItem.setGenAccFailedReason("");
        salesOrderItem.setStatus(SalesOrderStatusEnum.ACC_GEN.getValue());
        salesOrderItem.setGenAccFailedReason("");
        BeanUtils.copyProperties(salesOrderItem, salesOrderItemSaveParam);
        this.salesOrderItemHisService.update(salesOrderItem.getId(), salesOrderItemSaveParam);

        String apgenerateResult = this.generateApList(apamt,salesOrderItem,userVo);
        return rt;


    }
    /**
     * 供应商列表-分页
     *
     * @param params
     *
     * @return
     */
    @Override
    public  IPage<AccAccountingApHisVo> supplierSumPage(AccountingApSearchParam params, Integer current, Integer pageSize) {
        return this.mapper.supplierSumPage(new Page<>(current, pageSize), params);
    }

    @Override
    public List<AccAccountingApHisVo> suppierViewAccount(String supplierNo,String dateFrom,String dateTo){
        if(StringUtils.isNull(dateTo)){
            return this.mapper.suppierViewAccountDateFrom(supplierNo, dateFrom);
        }  else if(StringUtils.isNull(dateFrom)){
            return this.mapper.suppierViewAccountDateTo(supplierNo, dateTo);
        }else if(dateFrom.equals(dateFrom)) {
            return this.mapper.suppierViewAccount(supplierNo, dateFrom);
        }
        else{
            return this.mapper.suppierViewAccountBetween(supplierNo, dateFrom,dateTo);
        }

    }
    /**
     * 品牌排行列表-分页
     * @param params
     * @param current
     * @param pageSize
     * @return
     */
    @Override
    public IPage<AccAccountingApHisVo> brandRateView(AccountingApSearchParam params, Integer current, Integer pageSize){
        return this.mapper.brandRateView(new Page<>(current, pageSize), params);
    }

    /**
     * 供应商排行列表-分页
     * @param params
     * @param current
     * @param pageSize
     * @return
     */
    @Override
    public IPage<AccAccountingApHisVo> supplierRateView(AccountingApSearchParam params, Integer current, Integer pageSize) {
        return this.mapper.supplierRateView(new Page<>(current, pageSize), params);
    }


    /**
     * 产生财务结算数据
     *
     * @param salesOrderItem
     * @param materialBuyPriceSearchParam
     * @return
     */
    @Transactional(readOnly = false)
    @Override
    public Double getBuyTotalAmount(SalesOrderItemHisVo salesOrderItem, MaterialBuyPriceSearchParam materialBuyPriceSearchParam) {
        materialBuyPriceSearchParam.setWholeSaleQuantity(salesOrderItem.getQty());
        List<MaterialBuyPriceVo> materialBuyPrices = materialBuyPriceService.findAll(materialBuyPriceSearchParam);
        if (materialBuyPrices != null && materialBuyPrices.size() > 0) {
            MaterialBuyPriceVo materialBuyPriceVo = materialBuyPrices.get(0);
            if(!StringUtils.isNull(materialBuyPriceVo.getSettlePrice())) {
                Double apamt =NumberUtils.mul(Double.valueOf(materialBuyPriceVo.getSettlePrice()),salesOrderItem.getQty());
                salesOrderItem.setStatus(SalesOrderStatusEnum.ACC_GEN.getValue());
                salesOrderItem.setGenAccFailedReason("");
                salesOrderItem.setPrice(new BigDecimal(Double.valueOf(materialBuyPriceVo.getSettlePrice())));
                if(!StringUtils.isNull(materialBuyPriceVo.getCustRelSalesPrice())){
                    //   Double aramt =NumberUtils.mul(Double.valueOf(materialBuyPriceVo.getCustRelSalesPrice()),salesOrderItem.getQty());
                    salesOrderItem.setAmtGenAr(Double.valueOf(materialBuyPriceVo.getCustRelSalesPrice())) ;// 与营销委结算价
                }
                return apamt;
            }else
                return 0.0;

        } else {
            if(!StringUtils.isNull(materialBuyPriceSearchParam.getCsaSpuCode())){
                materialBuyPriceSearchParam.setCsaSkuCode("通用");
                materialBuyPriceSearchParam.setMaterialMapId(null);
                materialBuyPrices = materialBuyPriceService.findAll(materialBuyPriceSearchParam);
                MaterialBuyPriceVo materialBuyPriceVo = null;
                if (materialBuyPrices != null && materialBuyPrices.size() > 0) {
                    materialBuyPriceVo = materialBuyPrices.get(0);
                    if(!StringUtils.isNull(materialBuyPriceVo.getSettlePrice())) {
                        Double apamt =NumberUtils.mul(Double.valueOf(materialBuyPriceVo.getSettlePrice()),salesOrderItem.getQty());
                        salesOrderItem.setStatus(SalesOrderStatusEnum.ACC_GEN.getValue());
                        salesOrderItem.setGenAccFailedReason("");
                        if(!StringUtils.isNull(materialBuyPriceVo.getCustRelSalesPrice())){
                            //  Double aramt =NumberUtils.mul(Double.valueOf(materialBuyPriceVo.getCustRelSalesPrice()),salesOrderItem.getQty());
                            salesOrderItem.setAmtGenAr(Double.valueOf(materialBuyPriceVo.getCustRelSalesPrice())) ;// 与营销委结算价
                        }
                        salesOrderItem.setPrice(new BigDecimal(Double.valueOf(materialBuyPriceVo.getSettlePrice())));
                        return apamt;
                    }else
                        return 0.0;

                }else{

                    salesOrderItem.setErrorCode("203");
                    String msg = "203-订单号：".concat(salesOrderItem.getCustSalesOrderNo())
                            .concat(salesOrderItem.getCustSpuId()).concat("无法找到常规价格。");
                    salesOrderItem.setGenAccFailedReason(msg);

                    salesOrderItem.setStatus(SalesOrderStatusEnum.ACC_FAILED.getValue());
                    return 0.0;
                }
            }
            else{
                salesOrderItem.setErrorCode("203");
                String msg = "203-订单号：".concat(salesOrderItem.getCustSalesOrderNo())
                        .concat(salesOrderItem.getCustSpuId()).concat("无法找到常规价格。");
                salesOrderItem.setGenAccFailedReason(msg);
                salesOrderItem.setStatus(SalesOrderStatusEnum.ACC_FAILED.getValue());
                return 0.0;
            }
        }

    }
}
